<template>
  <div class="box">
    <div class="jeecg-basic-table-form-container">
      <el-form style="display: flex; margin-top: 14px" ref="formRef" :model="queryParam">
        <el-form-item label="渠道" name="channelId">
          <el-select clearable v-model="queryParam.channelId" placeholder="请选择" style="width: 256px">
            <el-option v-for="item in channelArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型" name="orderType">
          <el-select clearable v-model="queryParam.orderType" placeholder="请选择" style="width: 256px">
            <el-option v-for="item in orderTypeArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台" name="platformId">
          <el-select clearable v-model="queryParam.platformId" placeholder="请选择" style="width: 256px">
            <el-option v-for="item in platFormArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车型" name="vehicleTypeId">
          <el-select filterable clearable v-model="queryParam.vehicleTypeId" placeholder="请选择" style="width: 256px">
            <el-option v-for="item in carTypeArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="cityId">
          <el-select filterable clearable v-model="queryParam.cityId" placeholder="请选择" style="width: 256px">
            <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!--查询区域-->
    <dateModal ref="searchModal" @handleCheckDay="handleCheckDay" @handleSearchDate="handleSearchDate"></dateModal>
    <div class="time_case">
      <div :class="{ selected: selectTimes[i] }" class="item" v-for="(item, i) in timeOnes" :key="item.id" @click="handleTimeClick(i, item.start, item.end)">
        <div class="time">
          <div>{{ item.start }}-</div>
          <div>{{ item.end }}</div>
        </div>
        <div v-if="handleCheckActive(item.start, item.end)">总库存:{{ handleCheckText(item.start, item.end).num }}</div>
        <div v-else class="num">不限</div>
      </div>
    </div>
    <div class="btn_case">
      <el-button type="primary" @click="selectAlls(true)">全选</el-button>
      <el-button type="danger" @click="selectAlls(false)">清空</el-button>
    </div>

    <div class="bottom_box">
      <div class="case">
        <div>时段库存总数:</div>
        <el-input placeholder="请输入" v-model="orderNum"></el-input>
        <el-checkbox v-model:checked="isCheck">不限库存</el-checkbox>
        <el-button type="primary" @click="submitBtn">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" name="insurance-insurance" setup>
import { ref, reactive, onMounted } from "vue";
// import { saveOrUpdate, detail, getCity } from "../configApi";
import dateModal from "./dateModal.vue";
import { useRoute, useRouter } from "vue-router";
import {
  bizTypeEnum,
  orderTypeEnum,
  platFormEnum,
  channelEnum,
  bizTypeArr,
  orderTypeArr,
  platFormArr,
  channelArr,
  orderStatusArr,
  orderStatusEnum,
  carTypeArr,
  searchOrderArr,
  luggageEnum,
} from "@/enums/common";
import CommonApi from "@/api/common";
import JntApi from "@/api/jnt";
const route = useRoute();
const router = useRouter();
const isCheck = ref(false);
const timeOnes = ref([
  { start: "00:00", end: "00:59", id: 1 },
  { start: "01:00", end: "01:59", id: 2 },
  { start: "02:00", end: "02:59", id: 3 },
  { start: "03:00", end: "03:59", id: 4 },
  { start: "04:00", end: "04:59", id: 5 },
  { start: "05:00", end: "05:59", id: 6 },
  { start: "06:00", end: "06:59", id: 7 },
  { start: "07:00", end: "07:59", id: 8 },
  { start: "08:00", end: "08:59", id: 9 },
  { start: "09:00", end: "09:59", id: 10 },
  { start: "10:00", end: "10:59", id: 11 },
  { start: "11:00", end: "11:59", id: 12 },
  { start: "12:00", end: "12:59", id: 13 },
  { start: "13:00", end: "13:59", id: 14 },
  { start: "14:00", end: "14:59", id: 15 },
  { start: "15:00", end: "15:59", id: 16 },
  { start: "16:00", end: "16:59", id: 17 },
  { start: "17:00", end: "17:59", id: 18 },
  { start: "18:00", end: "18:59", id: 19 },
  { start: "19:00", end: "19:59", id: 20 },
  { start: "20:00", end: "20:59", id: 21 },
  { start: "21:00", end: "21:59", id: 22 },
  { start: "22:00", end: "22:59", id: 23 },
  { start: "23:00", end: "23:59", id: 24 },
]);
const MyDates = ref<any[]>([]); // 存储当前选中的日期
const activeTimes = ref<any[]>([]); // 存储所有已添加的时间段
const selectTimes = ref<boolean[]>([]); // 选中状态的数组时间
const orderNum = ref();
const searchTimes = ref([]); //查询出来的时间
const queryData: any = route.query.data;
const searchModal = ref();
const cityOptions = ref([]);

const queryParam = ref({
  channelId: undefined,
  orderType: undefined,
  platformId: undefined,
  vehicleTypeId: undefined,
  cityId: undefined,
});

onMounted(() => {
  CommonApi.getCity({ pageNo: 1, pageSize: 9999 }).then((res) => {
    if (res.code == 0) {
      cityOptions.value = res.result;
    }
  });
  console.log(route.query.data);
  if (route.query.data != undefined) {
    JntApi.priceConfigDetail(JSON.parse(queryData)).then((res) => {
      if (res.code == 0) {
        //控制是否显示库存初始化
        // searchTimes.value = res.result.data
        searchModal.value.handleSearchTimes(searchTimes.value);
      }
    });
    queryParam.value = JSON.parse(queryData);
  }
});

// 提取时间字符串中的时间部分（小时:分钟），并转换为只包含小时和分钟的字符串
function getTimePart(dateTimeString: any) {
  return dateTimeString.split(" ")[1].replace(/:\d{2}$/, ""); // 去除秒数，只保留小时和分钟
}

function handleCheckText(start: any, end: any) {
  // 使用 Array.prototype.find 方法来查找匹配的时间段
  return searchTimes.value.find((timeSlot) => {
    const slotStart = getTimePart(timeSlot.startTime);
    const slotEnd = getTimePart(timeSlot.endTime);

    // 检查时间范围是否重叠（只比较小时和分钟）
    return (
      (start >= slotStart && start <= slotEnd) || // 检查开始时间是否在范围内
      (end >= slotStart && end <= slotEnd) || // 检查结束时间是否在范围内
      (start <= slotStart && end >= slotEnd) // 一般情况下这种跨整个时段的比较对于小时:分钟来说不太可能，但保留以防数据异常
    );
  });
}
function handleCheckActive(start, end) {
  if (searchTimes.value == null) {
    return false;
  }

  // map searchTimes Array
  for (const timeSlot of searchTimes.value) {
    // split str item_time HH:MM
    const slotStartTime = timeSlot.startTime.split(" ")[1]; // "07:00:00" -> "07:00"
    const slotEndTime = timeSlot.endTime.split(" ")[1].slice(0, 5); // "07:59:59" -> "07:59"
    // 注意：这里我们假设 start 和 end 是有效的时间字符串，并且不需要进一步的验证
    if (
      (start >= slotStartTime && start <= slotEndTime) || // 检查开始时间是否在范围内
      (end >= slotStartTime && end <= slotEndTime) || // 检查结束时间是否在范围内
      (start <= slotStartTime && end >= slotEndTime) // 检查整个检查范围是否包含时间段（完全重叠）
    ) {
      return true; // 找到匹配的时间段，返回 true
    }
  }
  return false; // 没有找到匹配的时间段，返回 false
}
// 全选功能
const selectAlls = (status: any) => {
  selectTimes.value = []; //
  //判断时间段有多少个 有多少个就push 多少布尔值
  timeOnes.value.forEach((item) => {
    selectTimes.value.push(status);
  });
  // isCheck success or error
  if (status == true) {
    activeTimes.value = timeOnes.value;
  } else {
    activeTimes.value = [];
  }
};
//子组件日期选中
function handleCheckDay(times: any) {
  MyDates.value = times;
}
//子组件搜索事件
function handleSearchDate(time: any) {
  let data = {};
  if (queryData) {
    data = JSON.parse(queryData);
    data.time = time[time.length - 1];
    JntApi.priceConfigDetail(data).then((res) => {
      if (res.code == 0) {
        searchTimes.value = res.result.data;
      }
    });
  }
}

//click time change callBack
function handleTimeClick(index: any, start: any, end: any) {
  const timePeriod = { start, end }; // created times object
  const alreadyExists = activeTimes.value.some((item) => item.start === start && item.end === end);

  // falsechcek item_time delete time
  if (alreadyExists) {
    activeTimes.value = activeTimes.value.filter((period) => !(period.start === start && period.end === end));
  } else {
    // true check add time
    activeTimes.value.push(timePeriod);
  }
  selectTimes.value[index] = !selectTimes.value[index];
}

//click confirm btn handle
function submitBtn() {
  if (!queryParam.value.channelId) {
    ElMessage.error("请选择渠道");
    return;
  }
  if (!queryParam.value.orderType) {
    ElMessage.error("请选择订单类型");
    return;
  }
  if (!queryParam.value.platformId) {
    ElMessage.error("请选择平台");
    return;
  }
  if (!queryParam.value.vehicleTypeId) {
    ElMessage.error("请选择车型");
    return;
  }
  if (!queryParam.value.cityId) {
    ElMessage.error("请选择城市");
    return;
  }

  const data = transFormDate(MyDates.value, activeTimes.value);
  if (!data.length) {
    ElMessage.error("请选择日期和时间");
    return;
  }
  if (isCheck.value == false && !orderNum.value) {
    ElMessage.error("请输入库存数量");
    return;
  }

  let obj;
  if (queryData) {
    obj = {
      dates: data,
      num: isCheck.value ? -1 : orderNum.value,
      vehicleTypeId: JSON.parse(queryData).vehicleTypeId,
      orderType: JSON.parse(queryData).orderType,
      cityId: JSON.parse(queryData).cityId,
      channelId: JSON.parse(queryData).channelId,
      platformId: JSON.parse(queryData).platformId,
    };
  } else {
    console.log(queryParam.value);

    obj = { ...queryParam.value, dates: data, num: isCheck.value ? -1 : orderNum.value };
  }
  JntApi.priceConfigEdit(obj).then((res) => {
    if (res.code == 0) {
      ElMessage.success(res.message);
      setTimeout(() => {
        router.go(-1);
      }, 1000);
    } else {
      ElMessage.error(res.message);
    }
  });
}

const transFormDate = (dates, timeSlots) => {
  const result: any = [];
  dates.forEach((date) => {
    timeSlots.forEach((timeSlot) => {
      const startTime = `${date} ${timeSlot.start}:00`;
      const endTime = `${date} ${timeSlot.end}:59`;
      // 直接将字符串添加到结果数组中
      result.push({ startTime: startTime, endTime: endTime });
    });
  });

  return result;
};
</script>

<style lang="scss" scoped>
.box {
  padding: 0 80px;
  .time_case {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    //选中状态的样式
    .selected {
      background: #ffebea;
      border: 1px solid red !important;
      color: red;
    }
    .item {
      border: 1px solid #ccc;
      width: 10vw;
      padding: 6px 0;
      text-align: center;
      margin-top: 1px;
      margin-right: 1px;
      font-size: 12px;
      .time {
        display: flex;
        justify-content: center;
      }
      .num {
        color: #1f48dd;
      }
    }
  }
  .btn_case {
    margin-top: 14px;
    display: flex;
    justify-content: flex-end;
  }
  .bottom_box {
    justify-content: center;
    .case {
      display: flex;
      align-items: center;
      .el-input {
        width: 140px;
      }
    }
  }
}
</style>
